//
//  UserEditInfoCollionView.m
//  CheekiOS
//
//  Created by mac on 2017/6/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UserEditInfoCollionView.h"
//导航栏
#import "UINavigationBar+Transparent.h"
//状态瀑布流
#import "UserEditCollectionLayout.h"
#import "FWBCollectionViewCell.h"
//Cell 个人资料
#import "UserEditInfodataCell.h"
//公开相册
#import "UserEditPhotoCell.h"

#import "MJPhotoBrowser.h"
//状态详情
#import "FriendNewDetailsViewController.h"
//修改个人信息页
#import "UserEditViewController.h"
//修改头部
#import "UserCoverGroundViewController.h"

static NSString * ident = @"FWBCollectionViewCellIdent";
static NSString * UserEditInfodataCellIdent = @"UserEditInfodataCellIdent";
static NSString * CellIdentifier = @"PPImageScrollingCellIdent";
static NSString * titleCellident = @"titleCellIdent";


static CGFloat kHomeImgHeight = 260;

#define ValidStr(f) (f!=nil && [f isKindOfClass:[NSString class]] && ![f isEqualToString:@""])


@interface UserEditInfoCollionView ()<UICollectionViewDelegate,UICollectionViewDataSource,UserEditInfodataCellDelegate,UserEditPhotoCellDelegate,CAAnimationDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,MJPhotoBrowserDelegate>
/** 瀑布流约束 */
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, strong) UserEditCollectionLayout * collectionLayout;
/** 头部图片 */
@property (nonatomic, strong) UIImageView * headerImageView;
/** 状态数据 */
@property (nonatomic, strong) NSMutableArray * dataSource;
/** 动态模型 */
@property (nonatomic, strong) HRSDUserInfo *dynamicModel;
/** 图片数组 */
@property (nonatomic, strong) NSMutableArray *photoArr;



@property (nonatomic, strong) MJPhotoBrowser *browser;
@property (nonatomic, strong) NSString *MJphotoDelete;
@end

@implementation UserEditInfoCollionView


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTranslucent:YES];
    [self.navigationController.navigationBar js_setBackgroundColor:[UIColor clearColor]];
    
    [self setNavgationBarHidden];
    [self setNavgationBarHiddenNo];
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName : FontP(15)};

    [self setTabaritmimageStr:@"back_w"];
    
    [self updateSinfoUser];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar js_reset];
    
}
//让HeaderimageView去最下层
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (self.collectionView) {
        [self.collectionView sendSubviewToBack:self.headerImageView];
    }
    
}

-(void)backgroundImageChange{
    
    UserCoverGroundViewController *UCVC = [[UserCoverGroundViewController alloc] init];
    
    [self.navigationController pushViewController:UCVC animated:YES];
    
    

    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _MJphotoDelete = @"";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeListRequest) name:@"NotificationUserstateRequestAction" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSinfoUser) name:@"NotificationUserCoverimageUpdate" object:nil];

    
    self.title = _infoModel.nickName;
    
    [self configColectionView];
}

- (void)configColectionView{
    
    
    
    self.collectionLayout = [[UserEditCollectionLayout alloc] init];
    self.collectionLayout.lineNumber = 2; //列数
    self.collectionLayout.rowSpacing = 10; //行间距
    self.collectionLayout.lineSpacing = 10; //列间距
    self.collectionLayout.sectionInset = UIEdgeInsetsMake(10, 15, 10, 15);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight) collectionViewLayout:self.collectionLayout];
    [self.collectionView registerClass:[UserEditInfodataCell class] forCellWithReuseIdentifier:UserEditInfodataCellIdent];
    [self.collectionView registerClass:[UserEditPhotoCell class] forCellWithReuseIdentifier:CellIdentifier];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:titleCellident];
    [self.collectionView registerClass:[FWBCollectionViewCell class] forCellWithReuseIdentifier:ident];
    [self.collectionLayout registerClass:[UICollectionViewCell class] forDecorationViewOfKind:@"imgaeViewcell"];
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.view addSubview:self.collectionView];
    
    //返回每个cell的高   对应indexPath
    __weak typeof (self)weakSelf = self;
    [self.collectionLayout computeIndexCellHeightWithWidthBlock:^CGFloat(NSIndexPath *indexPath, CGFloat width) {
        
        if (indexPath.section == 0) {
            if (_infoModel) {
                int lines = 0;
                if (_infoModel.skill.length > 0) {
                    lines++;
                }
                if (ValidStr(_infoModel.job) || ValidStr(_infoModel.affection) || ValidStr(_infoModel.height) || ValidStr(_infoModel.weight)) {
                    lines++;
                }
                return firstSectionCellH*SCREEN_WIDTH_RATIO47 + oneLineHeight*lines;
            }
            return firstSectionCellH*SCREEN_WIDTH_RATIO47;
        }
        if (indexPath.section == 1) {
            
            CGFloat secondSectionCellH = kEditPhotoMargic * 3 + kEditPhotoTitleH;
            if (_infoModel.publicPhotoList.count > 0) {
                int line = ((int)_infoModel.publicPhotoList.count + 1)/4;
                int index = ((int)_infoModel.publicPhotoList.count + 1)%4;
                
                if (index == 0) {
                    secondSectionCellH += (kEditPhotoImgHeight*line + kEditPhotoImgMargicY*(line-1));
                }else{
                    secondSectionCellH += (kEditPhotoImgHeight*(line+1) + kEditPhotoImgMargicY*line);
                }
            }
            
            if (_infoModel.publicPhotoList.count >= 16) {
                secondSectionCellH = secondSectionCellH - kEditPhotoImgHeight-kEditPhotoImgMargicY;
            }
            if (_infoModel.publicPhotoList.count <= 0) {
                secondSectionCellH = kEditPhotoImgHeight+secondSectionCellH;

            }
            
            return secondSectionCellH;
        }
        if (indexPath.section == 2){
            return sectionsectioncellHH;
        }
        

        if (weakSelf.dataSource.count==0) {
            return 0;
        }
        HRTimeLineModel *timeLineModel = self.dataSource[indexPath.row];
        
        Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
        
        if (model.img.length > 0 && model.content.length > 0) {
            return (cellTextH + cellImageH+cellHeadTuneH)*SCREEN_WIDTH_RATIO47;
        }
        if (model.img.length > 0) {
            return (cellImageH+cellHeadTuneH)*SCREEN_WIDTH_RATIO47;
        }
        return (cellTextH+cellHeadTuneH)*SCREEN_WIDTH_RATIO47;
    }];
    
    
    self.collectionView.backgroundColor = ColorI(0xf6f6f6);
    //头部
    _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kHomeImgHeight*SCREEN_WIDTH_RATIO47, self.view.frame.size.width, kHomeImgHeight*SCREEN_WIDTH_RATIO47)];
    
    _headerImageView.contentMode = UIViewContentModeScaleAspectFill;
    _headerImageView.clipsToBounds = YES;
    _headerImageView.userInteractionEnabled = YES;
    
    UIView *view = [UIView new];
    [self.headerImageView addSubview:view];
    view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.top.mas_equalTo(self.headerImageView);
    }];
    UIButton *v= [UIButton new];
    v.backgroundColor = [UIColor clearColor];
    v.frame = CGRectMake(0, 0, KScreenWidth, self.headerImageView.height);
    [view addSubview:v];
    [v addTarget:self action:@selector(backgroundImageChange) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.collectionView setContentInset:UIEdgeInsetsMake(kHomeImgHeight*SCREEN_WIDTH_RATIO47, 0, 0, 0)];
    [self.collectionView addSubview:_headerImageView];
    
    

    [self activeListRequest];

    CGFloat videoFont ;
    
    if (iPhone5) {
        videoFont = 8;
    }else if (iPhone6){
        videoFont = 9;
        
    }else {
        videoFont = 11;
        
    }
    
    
    UIButton *videobtn = [UIButton buttonWithType:UIButtonTypeCustom];
    videobtn.titleLabel.font = FontBold(videoFont);
    if ([_infoModel.videoStatus isEqualToString:@"1"]) {
        [videobtn setImage:[UIImage imageNamed:@"stranger_play_att"] forState:UIControlStateNormal];
        
        [videobtn setTitle:@"视频已认证" forState:UIControlStateNormal];
        
    } else {
        [videobtn setImage:[UIImage imageNamed:@"stranger_id_wa_button"] forState:UIControlStateNormal];
        
        [videobtn setTitle:@"视频未认证" forState:UIControlStateNormal];
    }
    
    videobtn.imageEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
    videobtn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -6);
    
    [videobtn setTitleColor:TheLinColor forState:UIControlStateNormal];
    videobtn.layer.cornerRadius = 10.0;
    videobtn.layer.borderWidth = 0.5f;
    videobtn.layer.borderColor = [[UIColor whiteColor]CGColor];
    [_headerImageView addSubview:videobtn];
    
    [videobtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerImageView).offset(-15*SCREEN_WIDTH_RATIO47);
        make.width.mas_equalTo(80*SCREEN_WIDTH_RATIO47);
        make.height.mas_equalTo(20*SCREEN_WIDTH_RATIO47);
        make.bottom.equalTo(_headerImageView.mas_bottom).offset(-84*SCREEN_WIDTH_RATIO47);
    }];
    

//   for (NSDictionary *dic in _infoModel.publicPhotoList) {
//       [_photoArr addObject:dic];
//   }
    
    UIButton *cardButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cardButton.titleLabel.font = FontBold(videoFont);
    if ([_infoModel.cardImgStatus isEqualToString:@"1"]) {
        [cardButton setTitle:@"身份已认证" forState:UIControlStateNormal];
        [cardButton setImage:[UIImage imageNamed:@"stranger_id_att"] forState:UIControlStateNormal];
        
    } else {
        [cardButton setTitle:@"身份未认证" forState:UIControlStateNormal];
        [cardButton setImage:[UIImage imageNamed:@"stranger_id_wa_button"] forState:UIControlStateNormal];
    }
    [cardButton setTitleColor:TheLinColor forState:UIControlStateNormal];
    cardButton.layer.cornerRadius = 10.0;
    cardButton.layer.borderWidth = 0.5f;
    cardButton.layer.borderColor = [[UIColor whiteColor]CGColor];
    cardButton.imageEdgeInsets = UIEdgeInsetsMake(0, -8, 0, 0);
    cardButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -6);
    
    [_headerImageView addSubview:cardButton];
    
    [cardButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerImageView).offset(-15*SCREEN_WIDTH_RATIO47);
        make.width.mas_equalTo(80*SCREEN_WIDTH_RATIO47);
        make.height.mas_equalTo(20*SCREEN_WIDTH_RATIO47);
        make.top.equalTo(videobtn.mas_bottom).offset(5);
    }];
    
    

    
}

#pragma mark =============CollectionDelegate dataSource================
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 4;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 1;
    }else if (section == 2){
        return 1;
    }else{
        return self.dataSource.count;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        UserEditInfodataCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:UserEditInfodataCellIdent forIndexPath:indexPath];
        
        cell.infoModel = _infoModel;
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section == 1){
        
        UserEditPhotoCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        
        cell.delegate = self;
        cell.headerPhoto =_infoModel.photo;

        cell.photoArr = _infoModel.publicPhotoList;
        
        cell.backgroundColor = [UIColor whiteColor];
        [cell setTag:[indexPath section]];

        return cell;
    }else if (indexPath.section == 2){
        UICollectionViewCell  *cell = [collectionView dequeueReusableCellWithReuseIdentifier:titleCellident forIndexPath:indexPath];
        
        UILabel *title = [[UILabel alloc] init];
        title.text = @"我的动态";
        
        title.textAlignment = NSTextAlignmentLeft;
        title.font = [UIFont systemFontOfSize:16];
        
        title.frame = CGRectMake(15, 20, cell.width, 30);
        
        title.textColor = [UIColor blackColor];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.frame  = CGRectMake(50, title.bottom+40, KScreenWidth-100, 140);
        imgView.image = [UIImage imageNamed:@"logo"];
        
        [cell.contentView addSubview:title];
        //        [cell.contentView addSubview:imgView];·
        
        return cell;
    }else{
        
        FWBCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ident forIndexPath:indexPath];
        
        HRTimeLineModel *timeLineModel = self.dataSource[indexPath.row];
        Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
        
        cell.model = model;
        return cell;
        
        
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.section);
    if (indexPath.section == 0) {
        UserEditViewController *vc = [[UserEditViewController alloc]init];
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if(indexPath.section == 3){
        
        HRTimeLineModel *timeLineModel = self.dataSource[indexPath.row];
        Active *model = [Active getActiveWithDictionary:(NSDictionary *)timeLineModel.active];
        FriendNewDetailsViewController *vc = [[FriendNewDetailsViewController alloc] init];
        vc.CircleId = [NSString stringWithFormat:@"%ld",(long)model.circleId];
        
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}
#pragma mark ===============头部滑动===============
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY >0) {
        CGFloat alpha = (offsetY+64) / 16 ;
        alpha = MIN(alpha, 1.0);
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(15)};
        
        [self setTabaritmimageStr:@"back"];
        
        [self.navigationController.navigationBar js_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha]];
        
    } else {
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName : FontP(15)};
        
        [self setTabaritmimageStr:@"back_w"];
        
        [self.navigationController.navigationBar js_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
    }
    
    //通过滑动的便宜距离重新给图片设置大小
    CGFloat yOffset = scrollView.contentOffset.y;
    if(yOffset<-kHomeImgHeight*SCREEN_WIDTH_RATIO47){
        
        if (self.headerImageView) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CGRect frame = self.headerImageView.frame;
                frame.origin.y = yOffset;
                frame.size.height = -yOffset;
                self.headerImageView.frame = frame;
            });
            
        }
        
    }
    
}

#pragma mark ===================数据===========请求===========
//个人动态数据
-(void)activeListRequest{
    WEAKSELF
    _dataSource = [[NSMutableArray alloc] init];

    [HQHttpManager activeListWithUid:[HQHttpManager getUserId] herId:[HQHttpManager getUserId] page:@1
                        successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                            NSLog(@"陌生人朋友圈状态===========%@",resultDic);
                            if (isSuccess) {
                                
                                [self.dataSource removeAllObjects];
                            }
                            NSArray *array = resultDic[@"res"];
                            for (NSDictionary *dic in array) {
                                HRTimeLineModel *model = [HRTimeLineModel getTimeLineModelWithDictionary:dic];
                                [self.dataSource addObject:model];
                            }
                            
                            
                            [weakSelf.collectionView reloadData];

                            
            }];
}


#pragma mark ==================添加图片方法==================
- (void)addPhotoBtnClickBtn:(UIButton *)sender{
    [self getAddPhotoDate];
}
#pragma mark ==================点击相册方法==================

- (void)userEditPhotoCell:(UserEditPhotoCell *)cell didClickAddBtn:(UIButton *)sender{

}
- (void)userEditPhotoCell:(UserEditPhotoCell *)cell didClickImg:(UIButton *)sender{

//    NSIndexPath * indexPath = [self.collectionView indexPathForCell:cell];
    NSInteger count = _infoModel.publicPhotoList.count;
    
    _photoArr = [NSMutableArray arrayWithCapacity:count];
    
    // 1.封装图片数据
    if (count > 0) {
        for (int i = 0; i<count; i++) {
            //公开相册有数据
            _MJphotoDelete = @"1";

            NSDictionary *images = [_infoModel.publicPhotoList objectAtIndex:i];
            NSString *url = [images objectForKey:@"url"];
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HttpImgUrlString,url]]; // 图片路径
            [_photoArr addObject:photo];
        }
    }else{
        //无数据
        _MJphotoDelete = @"0";

        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HttpImgUrlString,_infoModel.photo]]; // 图片路径
        [_photoArr addObject:photo];
    }
    
    // 2.显示相册
    _browser = [[MJPhotoBrowser alloc] init];
    _browser.delegate = self;
    _browser.strBtnType = @"1";
    _browser.currentPhotoIndex = sender.tag-1000; // 弹出相册时显示的第一张图片是？
    _browser.photos = _photoArr; // 设置所有的图片
    [_browser show];


}

-(void)DeleteActin:(UIButton *)sender{
 
    if ([_MJphotoDelete isEqualToString:@"0"]) {
        [SVProgressHUD showWithStatus:@"公开相册无图片时，默认头像不可删除"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
            [SVProgressHUD dismiss];
        
        });
    }else{
        
        NSDictionary *dataDic = _infoModel.publicPhotoList[sender.tag];
        
        NSString *strPhotoId = [NSString stringWithFormat:@"%@",dataDic[@"photoId"]] ;
        
        [HcardHttpmanager deletePhotoWithPhotoId:[strPhotoId integerValue] Success:^(id result) {
            if(result){
                
                [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
                    self.infoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
                    
                    
                    [self.collectionView reloadData];
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@",error.description);
                }];
            }
        } failure:^(NSError *error) {
            
        }];
    }

}

#pragma mark ============添加图片方法===========
-(void)getAddPhotoDate{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picekerVc = [[UIImagePickerController alloc] init];
        picekerVc.sourceType = UIImagePickerControllerSourceTypeCamera;
        picekerVc.delegate = self;
        picekerVc.allowsEditing = YES;

        [self presentViewController:picekerVc animated:YES completion:nil];
     

    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *picekerVc = [[UIImagePickerController alloc] init];
        picekerVc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        picekerVc.delegate = self;
        picekerVc.allowsEditing = YES;

        [self presentViewController:picekerVc animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:^{
    }];

}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出
        UIImage* oldImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        
        
        UIImageOrientation imageOrientation = oldImage.imageOrientation;
        
        UIImage * image;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(oldImage.size);
            [oldImage drawInRect:CGRectMake(0, 0, oldImage.size.width, oldImage.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }else{
            image = oldImage;
        }
        NSData *data;
        
        if (UIImagePNGRepresentation(image) == nil){
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else{
            data = UIImagePNGRepresentation(image);
        }
        
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.jpg
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        UIImage * img = [UIImage imageWithData:data];
        
    [HcardHttpmanager upLoadPhotosWithFile:img WithBelong:@"photo" WithToAublum:KToAublumYES WithAlbumId:_infoModel.publicAlbumId success:^(id sucess) {
        [SVProgressHUD dismiss];
        if(sucess){
            [self updateSinfoUser];
        }else{
            [SVProgressHUD showErrorWithStatus:@"上传失败!"];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"上传失败!"];
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
    [SVProgressHUD showWithStatus:@"正在上传"];
    }
}

#pragma mark - =================Sinfo 获取个人信息===========
-(void)updateSinfoUser{
        WEAKSELF
            [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
                
                weakSelf.infoModel = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
                
                [_headerImageView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(weakSelf.infoModel.background)] placeholderImage:[UIImage imageNamed:@"llustration"]];
               
                [weakSelf.collectionView reloadData];
                
            } failure:^(NSError *error) {
                NSLog(@"%@",error.description);
            }];
            
    }




@end
